<template>
    <div class="module5-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>换电柜电池统计</span>
                    <el-button type="primary" @click="openAddDialog">添加数据</el-button>
                </div>
            </template>
            
            <el-table 
                :data="sortedTableData" 
                style="width: 100%"
                stripe
                border
            >
                <el-table-column prop="cabinetName" label="换电柜名称"  />
                <el-table-column prop="batteryCount" label="电池数"  sortable />
                <el-table-column label="操作" >
                    <template #default="{ row, $index }">
                        <el-button type="primary" size="small" @click="editRow(row, $index)">编辑</el-button>
                        <el-button type="danger" size="small" @click="deleteRow($index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加/编辑弹框 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="dialogTitle" 
            width="500px"
            @close="resetForm"
        >
            <el-form 
                ref="formRef" 
                :model="formData" 
                :rules="formRules" 
                label-width="100px"
            >
                <el-form-item label="换电柜名称" prop="cabinetName">
                    <el-input v-model="formData.cabinetName" placeholder="请输入换电柜名称" />
                </el-form-item>
                <el-form-item label="电池数" prop="batteryCount">
                    <el-input-number 
                        v-model="formData.batteryCount" 
                        :min="0" 
                        :max="999" 
                        placeholder="请输入电池数"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveData">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { updateDataClassify } from '@/api/port'

// 表格数据
const tableData = ref<Array<{
    cabinetName: string
    batteryCount: number
}>>([])

// 按电池数从小到大排序的计算属性
const sortedTableData = computed(() => {
    return [...tableData.value].sort((a, b) => a.batteryCount - b.batteryCount)
})

// 弹框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加换电柜数据')
const isEdit = ref(false)
const editIndex = ref(-1)

// 表单数据
const formData = reactive({
    cabinetName: '',
    batteryCount: 0
})
// 数字范围验证函数
const validateNumber = (rule: any, value: number, callback: (error?: Error) => void) => {
    if (value === null || value === undefined) {
        callback(new Error('请输入数字'))
    } else if (value < 0) {
        callback(new Error('请输入大于等于0的数字'))
    } else if (value > 12) {
        callback(new Error('请输入小于12的数字'))
    } else {
        callback()
    }
}

// 表单验证规则
const formRules: FormRules = {
    cabinetName: [
        { required: true, message: '请输入换电柜名称', trigger: 'blur' },
        { min: 2, max: 50, message: '换电柜名称长度在2-50个字符', trigger: 'blur' }
    ],
    batteryCount: [
        { required: true, message: '请输入电池数', trigger: 'blur' },
        { validator: validateNumber, trigger: 'blur' }
    ]
}

// 表单引用
const formRef = ref<FormInstance>()

// 打开添加弹框
const openAddDialog = () => {
    dialogTitle.value = '添加换电柜数据'
    isEdit.value = false
    dialogVisible.value = true
}

// 编辑行数据
const editRow = (row: any, index: number) => {
    dialogTitle.value = '编辑换电柜数据'
    isEdit.value = true
    editIndex.value = index
    Object.assign(formData, row)
    dialogVisible.value = true
}

// 删除行数据
const deleteRow = (index: number) => {
    ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        tableData.value.splice(index, 1)
        ElMessage.success('删除成功')
        updateData()

    })
}

// 保存数据
const saveData = async () => {

    formRef.value?.validate(async (valid) => {
        if (valid) {
            if (isEdit.value) {
                // 编辑模式
                Object.assign(tableData.value[editIndex.value], formData)
                ElMessage.success('修改成功')
            } else {
                // 添加模式
                tableData.value.push({ ...formData })
                ElMessage.success('添加成功')
            }

            // 调用保存接口
            await updateData()
            console.log('保存配送数据配置:', tableData.value)
            dialogVisible.value = false
            resetForm()
            console.log('换电柜数据已保存:', formData)
        }
    })
}

// 重置表单
const resetForm = () => {
    formRef.value?.resetFields()
    Object.assign(formData, {
        cabinetName: '',
        batteryCount: 0
    })
    isEdit.value = false
    editIndex.value = -1
}
const updateData = async () => {
    await updateDataClassify({
        id: 3,
        key: 'module5',
        value: tableData.value
    })
    console.log('保存配送数据配置:', tableData.value)
}
// 初始化函数
const init = (module: any) => {
    console.log('Module5 初始化完成')
    if(module){
        tableData.value = module
    }
}

// 暴露初始化函数
defineExpose({
    init
})
</script>

<style scoped>
.module5-container {
    padding: 20px;
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        span {
            font-size: 16px;
            font-weight: bold;
        }
    }
    
    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
}
</style>